import * as fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

import { absolutePosixFilePath } from '@contentlayer/utils'
import * as core from 'contentlayer/core'
import { defineDocumentType, makeSource } from 'contentlayer/source-files'
import { expect, test } from 'vitest'

test('empty content folder', async () => {
  const Post = defineDocumentType(() => ({
    name: 'Post',
    filePathPattern: '**/*.md',
    fields: {},
  }))

  const testDirPath = fileURLToPath(new URL('.', import.meta.url))

  await fs.rm(path.join(testDirPath, '.contentlayer'), { recursive: true, force: true })

  process.env['PWD'] = testDirPath

  const source = await makeSource({
    contentDirPath: path.join(testDirPath, 'posts'),
    documentTypes: [Post],
  })(undefined)

  await core.runMain({ tracingServiceName: 'contentlayer-test', verbose: false })(
    core.generateDotpkg({
      config: { source, esbuildHash: 'STATIC_HASH', filePath: absolutePosixFilePath('/not/used') },
      verbose: true,
    }),
  )

  const generatedIndexJsFile = await fs.readFile(
    path.join(testDirPath, '.contentlayer', 'generated', 'Post', '_index.mjs'),
    'utf8',
  )

  expect(generatedIndexJsFile).toMatchInlineSnapshot(`
    "// NOTE This file is auto-generated by Contentlayer
    
    
    
    export const allPosts = []
    "
  `)

  const generatedIndexJsonFile = await fs.readFile(
    path.join(testDirPath, '.contentlayer', 'generated', 'Post', '_index.json'),
    'utf8',
  )

  expect(generatedIndexJsonFile).toMatchInlineSnapshot('"[]"')
})
